﻿function getDomainFromUrl(url) {
    var host = "null";
    if(typeof url == "undefined" || null == url) {
        url = window
        
        .location.href;
    }
    
    var regex = /.*\:\/\/([^\/]*).*/;
    var match = url.match(regex);
    if(typeof match != "undefined" && null != match) {
        host = match[1];
    }
    
    return host;
}


var shoppingSiteList = [
    "www.tmall.com",
    "www.taobao.com",
    "www.suning.com",
    "www.jd.com",
    "www.vip.com"
]


function isSHoppingSite(tabId, changeInfo, tab) {

    var isSHoppingSiteFlag = false;

    for(i=0;i<shoppingSiteList.length;i++) {
        if (shoppingSiteList[i] == getDomainFromUrl(tab.url).toLowerCase()) {
            isSHoppingSiteFlag = true;
        }
    }

    if(isSHoppingSiteFlag){
        chrome.tabs.executeScript(tabId, {code: "document.body.innerHTML='<div style=\"margin-top:100px;text-align:center;color:red;font-size:50px;\">谨防剁手，从我做起！！！<br /><br />by 伍咖</div>'"});
        chrome.tabs.executeScript(tabId, {code: "setTimeout(\"window.location.href='https://www.baidu.com'\", 3000)"});
    }
};

function init(i) {
    if(i == "1") {
        chrome.tabs.onUpdated.addListener(isSHoppingSite);
    }else {
        chrome.tabs.onUpdated.removeListener(isSHoppingSite);
    }
}

chrome.runtime.onMessage.addListener(function(request, sender, sendRequest){
    if(request.type !== "open") {
        return;
    }
    
    chrome.storage.sync.set({'open':request.i},function() {});
    init(request.i);
});


chrome.storage.sync.get("open", function(items) {  
    init(items.open);
});
